const fetchEventSource = (url, options) => {
  fetch(url, options)
    .then((response) => {
      if (response.status === 200) {
        options.onopen && options.onopen();
        return response.body;
      }
    })
    .then((rb) => {
      console.log(rb);
      const reader = rb.getReader();
      const push = () => {
        console.log("递归了");
        // done 为数据流是否接收完成，boolean
        // value 为返回数据，Uint8Array
        return reader.read().then(({ done, value }) => {
          if (done) {
            options.onclose && options.onclose();
            return;
          }
          options.onmessage && options.onmessage(parseEventData(new TextDecoder().decode(value)));

          // 持续读取流信息
          return push();
        });
      };
      // 开始读取流信息
      return push();
    })
    .catch((e) => {
      options.onerror && options.onerror(e);
    });
};

// 解析字符串并构建对象
function parseEventData(rawData) {
  var id = rawData.match(/id:(\d+)/)[1];
  var dataStartIndex = rawData.indexOf("data:") + 5;
  var dataEndIndex = rawData.indexOf("\n", dataStartIndex);
  var dataString = rawData.substring(dataStartIndex, dataEndIndex);
  var eventData = JSON.parse(dataString);

  var event = {
    id: id,
    data: eventData,
  };

  return event;
}